<template>
  <div class="publish-container">
    <!-- 卡片模式 -->
    <el-card>
      <!-- 卡片上部 -->
      <div slot="header">
        <!-- 面包屑导航 -->
        <el-breadcrumb>
          <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
          <el-breadcrumb-item>发布文章</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 发布文章_表单 -->
      <el-form ref="form" :model="article" label-width="80px" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="article.title" ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- <el-input type="textarea"></el-input> -->
          <quill-editor
          v-model="article.content"
          :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="封面">
          <el-radio-group v-model="article.cover.type" @change="typeChange">
            <el-radio :label="1" >单图</el-radio>
            <el-radio :label="3" >三图</el-radio>
            <el-radio :label="0" >无图</el-radio>
            <el-radio :label="-1" >自动</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 封面组件-->
        <el-form-item prop="cover">
          <el-row :gutter="20" v-if="article.cover.type !==-1">
            <el-col :span="5" v-for="(num,index) in article.cover.type" :key="num">
              <!-- 自定义组件使用v-model 原理把右侧的值，赋予给当前组件的value属性
                传入数据  内部必须叫 value 的props属性接收
              -->
              <MyCover @coverimg='coverImgFn' :index="index" v-model="article.cover.images[index]"/>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="频道" prop="channel_id">
          <el-select v-model="article.channel_id"  placeholder="请选择活动区域">
            <el-option
            v-for="item in channelArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="createFn(false)">发表</el-button>
          <el-button  @click="createFn(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { channelListAPI, addArticleAPI, articleByIdAPI, articleUpdateAPI } from '@/api/index'

// 富文本引入
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

// 引入公共的验证规则
import { articleAddRules } from '@/verify'

// 引入封面组件MyCover
import MyCover from '@/components/MyCover'
// import MyCover from '../../components/MyCover.vue'
export default {
  name: 'articleAdd',
  data () {
    return {
      article: {
        title: '',
        content: '',
        cover: {
          type: 0,
          images: []
        },
        channel_id: ''
      },
      channelArr: [],
      editorOption: {
        modules: {
          // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗, 斜体, 下划线, 删除线
            ['blockquote', 'code-block'], // 双引号和代码
            [{ header: 1 }, { header: 2 }], // h几字体图标
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表, 无序列表
            [{ indent: '-1' }, { indent: '+1' }], // 缩进-1, 缩进+1 按钮
            ['image'] // 图片插件
          ]
        }
      },
      rules: articleAddRules,
      artId: -1 // 正在编辑的文章id 如果为-1证明是发布
    }
  },
  methods: {
    createFn (bool) {
      // console.log(23)
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (this.artId !== -1) { // 如果id不是-1 就证明更新文章
          const [err, res] = await articleUpdateAPI(this.artId, { draft: bool }, this.article)
          if (!err) {
            // console.log(res.status)
          // await 成功后才会往下走
            if (bool === false && res.status === 201) {
              this.$message({
                message: '文章重新编辑成功',
                type: 'success'
              })
            } else {
              this.$message({
                message: '文章存入草稿成功',
                type: 'success'
              })
            }
            // 更新成功了跳转到文章列表
            this.$router.replace('/layout/articleList')
          }
        } else { // 否则就是新增
          const [err] = await addArticleAPI({ draft: bool }, this.article)
          if (err) return
          if (bool === false) {
            this.$message({
              message: '文章发表成功',
              type: 'success'
            })
          } else if (bool === true) {
            this.$message({
              message: '存入草稿成功',
              type: 'success'
            })
          }
        }

        // 组件内 data函数变量, 绑定到$data上
        // this.$options 获取的当前组件的export default后对象
        // this.$options.data() 调data函数执行, 原地得到return后的对象(带初值)

        // console.log(this.$options.data()) // 初始data对象
        // console.log(this.$data) // 绑定数据后的对象
        // console.log(this.$data.article) // 值
        // console.log(this.article) // 和上面相等, $data可以省略的

        // 总结: 原始初始值 this.$options.data()
        // 现在最新状态的值 this.$data

        // 口诀: 设置回初始值
        Object.assign(this.article, this.$options.data().article)

        // 为啥不用=, 要用Object.assign()
        // 用=可能造成对象的互相引用
        // Object.assign()会把后面的key和value直接"拷贝"给前面对象里的key和value上
        // article受影响, 页面也受影响(效果: 输入框的值又变成了最开始的空值)
      })
    },
    typeChange () {
      if (this.article.cover.type === 0 || this.article.cover.type === -1) {
        this.article.cover.images = []
      } else if (this.article.cover.type === 1) {
        this.article.cover.images = this.article.cover.images.slice(0, 1)
      }
    },
    coverImgFn (imgUrl, index) {
      // console.log(imgUrl)
      if (imgUrl === false) {
        this.article.cover.images[index] = undefined
      } else {
        this.article.cover.images[index] = imgUrl
      }
    }
  },
  async created () {
    const [err, res] = await channelListAPI()
    // console.log(res)
    if (!err) {
      this.channelArr = res.data.data.channels

      // 判断当前url有无id  id由文章列表 传入 this.$route.query.  id 接收   如果有就进入编辑状态 否则就是新发布的
      if (this.$route.query.id) {
        this.artId = this.$route.query.id
        const [err, artRes] = await articleByIdAPI(this.artId)
        if (!err) {
          // console.log(artRes)
          if (Object.keys(artRes.data.data).length === 0) {
            this.$message({
              message: '没有此文章-请确认id,将为您转跳文章列表',
              type: 'warning',
              onClose: () => {
                this.$router.push('/layout/articleList')
              }
            })
          } else {
            this.article = artRes.data.data
          }
        }
      }
    }
  },
  components: {
    quillEditor,
    MyCover
  }

}
</script>

<style lang="less" scoped >
  // 在父组件中去设置子组件的样式，加上/deep/ 实现穿透功能
    .publish-container /deep/ .ql-editor {
      height: 300px;
    }
    .publish-container /deep/ .ql-toolbar.ql-snow {
      padding: 0 8px;
    }
</style>
